package com.tyfspring.beans.support;

import cn.hutool.core.util.StrUtil;
import com.tyfspring.beans.DisposableBean;
import com.tyfspring.beans.config.BeanDefinition;
import com.tyfspring.beans.exception.BeansException;

import java.lang.reflect.Method;

/**
 * @Description 销毁方法有两种或者更多：实现DisposableBean接口，配置信息destroyMethod等。要进行统一处理
 * @Author shallow
 * @Date 2023/4/10 20:38
 */

public class DisposableBeanAdapter implements DisposableBean {

    private final Object bean;
    private final String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        //1.实现接口DisposableBean
        if (bean instanceof DisposableBean){
            ((DisposableBean) bean).destroy();
        }
        //2.配置信息destroy-method 避免二次执行销毁
        if(StrUtil.isNotEmpty(destroyMethodName)&&!(bean instanceof DisposableBean&&"destory".equals(this.destroyMethodName))){
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if(null == destroyMethod){
                throw new BeansException("Couldn't find a destroy method named '" +
                        destroyMethodName + "' on bean with name '" + beanName + "'");
            }
            destroyMethod.invoke(bean);
        }
    }
}
